package com.landun.market.web.controller;

import com.landun.market.exception.AuthenticationException;
import com.landun.market.pojo.Constants;
import com.landun.market.pojo.model.User;
import com.landun.market.service.ISecurityService;
import com.landun.market.util.HostUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Optional;

/**
 * @author jiang.chuan
 * @date 2018-05-05
 */
@Slf4j
@RestController
public class AbstractController {
    @Autowired
    protected HttpServletRequest httpRequest;

    @Autowired
    protected ISecurityService securityService;


    /**
     * 将URL上的字符串进行解码
     *
     * @param searchTerm 查询的字条串
     * @return 解码后的字符串
     */
    protected String decodeString(String searchTerm) {
        if (StringUtils.isNotBlank(searchTerm)) {
            try {
                return URLDecoder.decode(searchTerm.trim(), "UTF-8");
            } catch (UnsupportedEncodingException ex) {
                log.warn("字符串(" + searchTerm + ")解码错误", ex);
            }
        }
        return StringUtils.EMPTY;
    }

    /**
     * 根据授权令牌获取用户详情
     *
     * @return User
     */
    protected User getUser() {
        HttpServletRequest request = Optional.ofNullable(httpRequest).orElse(getRequest());
        if (null == request) {
            throw new AuthenticationException("授权令牌不能不空");
        }

        // 获取授权令牌
        String token = StringUtils.trimToEmpty(request.getHeader(Constants.TOKEN_PARA_NAME));
        if (StringUtils.isBlank(token)) {
            throw new AuthenticationException("授权令牌不能不空");
        }

        // 获取用户详情
        return Optional.ofNullable(securityService.getUserByToken(token, HostUtils.getRequestIp(request)))
                .orElseThrow(() -> new AuthenticationException("用户没有登陆"));
    }

    /**
     * @return HttpServletRequest
     */
    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
